% @brief OptimizingGroupP 用于GIA迭代相移
% @param AB 光强和调制度
% @param Phi 包裹相位
% @param Delta 四帧相移
% @param Q 麦克劳林的阶次
% @param 拍摄的现实条纹图
% @param Alpha 麦克劳林的系数
% @output 迭代后的[麦克劳林系数,包裹相位]
function [Alpha,Delta_iter] = OptimizingGroupS_LRD(A,B,Phi,Delta,Q,I,Alpha,Legd_Matrix)
    F = length(I);
    Delta_iter = cell(F,1);
    minAlpha = zeros(1,(Q+1)*(Q+2)/2) - inf;
    maxAlpha = zeros(1,(Q+1)*(Q+2)/2) + inf;
    lambda_max = 0.1;
    tol = 1e-4;
    max_iter = 200;
    [I_row,I_col] = size(I{1,1});
    Legd_Matrix_f = zeros(I_row, I_col, (Q+1)*(Q+2)/2);
    for f = 1:F
        r = rVector_S(A,B,Phi,Delta{f,1},I{f,1});
        J = JMatrix_S_LRD(B,Phi,Delta{f,1},Q,Legd_Matrix);
        alpha = Alpha{f,1};
        Alpha{f,1} = LSF_LM(J, r, alpha, minAlpha', maxAlpha', lambda_max, tol, max_iter);
%         Alpha{1,1}(:) = 0;
        %------------利用迭代出来的麦克劳林系数计算Delta--------
        for k = 1:(Q+1)*(Q+2)/2
            Legd_Matrix_f(:,:,k) = Alpha{f,1}(k)*Legd_Matrix(:,:,k);
        end
        Delta_iter{f,1} = sum(Legd_Matrix_f, 3);
%         Delta_iter{1,1}(:) = 0; %将第一帧设置为0
        Delta_iter{f,1} = Delta_iter{f,1} - Delta_iter{1,1};
%         mesh(Delta_iter{f,1});
%         Delta_iter{f,1}(Delta_iter{f,1}<0) = Delta_iter{f,1}(Delta_iter{f,1}<0) + 2*pi;
%         Delta_iter{f,1}(Delta_iter{f,1}>0) = Delta_iter{f,1}(Delta_iter{f,1}>0) - 2*pi;
        Delta_ = mean(mean(Delta_iter{f,1}));
        fprintf("第%d帧相移 %d \n",f,Delta_);
    end

end

